package sfs

import (
	"fmt"
	"os"
	"strings"
)

var TEMPLATE string = `
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>sfs</title>

</head>

<body>
    {{upload}}
    {{body}}
</body>
<script>

    function upload() {
        var file = document.getElementById("fileupload").files[0]
        if (!file) {
            console.log("无效文件");
        }

        var formData = new FormData()
        formData.append("file", file)

        var xhr = new XMLHttpRequest()
        xhr.open("POST", window.location.pathname, true)
        xhr.onload = function () {
            console.log("文件上传成功")
			location.reload()
        }

        xhr.send(formData)
    }

</script>
</html>
`

func BuildDirectoryView(path string, allawyUpload bool) string {
	file, e1 := os.Open("." + path)
	if e1 != nil {
		fmt.Println(e1.Error())
		return e1.Error()
	}

	dirs, e2 := file.Readdir(0)
	if e2 != nil {
		fmt.Println(e2.Error())
		return e2.Error()
	}

	routes := "<div>----------------------------------------</div>"
	if path != "/" {
		routes = routes + fmt.Sprintf("<a href='%s'>%s</a><br>", "../", "../")
	}

	for _, dir := range dirs {
		if dir.IsDir() {
			p := path + dir.Name() + "/"
			routes = routes + fmt.Sprintf("<a href='%s'>%s</a><br>", p, dir.Name()+"/")
		} else {
			p := path + dir.Name()
			routes = routes + fmt.Sprintf("<a href='%s'>%s</a><br>", p, dir.Name())
		}
	}

	view := strings.Replace(TEMPLATE, "{{body}}", routes, 1)
	if allawyUpload {
		view = strings.Replace(view, "{{upload}}", `<input type="file" id="fileupload" onchange="upload()" />`, 1)
	} else {
		view = strings.Replace(view, "{{upload}}", ``, 1)
	}

	return view
}
